//博客相关方法
const {execSQL} = require("../db/mysql");
const getList=(author, keyword)=>{
    //从数据库里拿数据
    let sql='select * from blogs where 1=1 ';
    if(author){
        sql+=`and author='${author}' `;
    }
    if(keyword){
        sql+=`and title like'%${keyword}%'`;
    }
    return execSQL(sql);

}
//获取博客详情数据
const getDetail=(id)=>{
    let sql='select * from blogs where 1=1 ';
    if(id){
        sql+=`and id='${id}'`;
    }
    execSQL(sql).then(rows=>{
        console.log(rows);
        return rows[0];
    });
    //return execSQL(sql);
}
//创建博客方法
const createNewBlog=(blogData={})=>{
    const title=blogData.title;
    const content=blogData.content;
    const author=blogData.author;
    const createdAt=Date.now();
    const sql=`insert into blogs (title,content,author,createAt) values ('${title}','${content}','${author}',${createdAt});`
     return execSQL(sql).then(insertedResult=>{
         console.log(insertedResult);
         return {
             id:insertedResult.insertId
         };
     });
}
//更新博客方法,防止没传参数，先设置为空
const updataedBlog=(id,blogData={})=>{
    const title=blogData.title;
    const content=blogData.content;
    const sql=`update blogs set title='${title}',content='${content}' where id=${id};`;
    return execSQL(sql).then(updateResult=>{
        console.log(updateResult);
        if(updateResult.affectedRows>0) return true;
        return false;
    });


}

//删除博客路由
const deleteBlogData=(id,author)=>{
    //每个人只能删除自己的博客

    const sql=`delete from blogs where id=${id} and author='${author}'`;
    return execSQL(sql).then(deleteResult=>{
        if(deleteResult.affectedRows>0) return true;
        return false;
    })
}
module.exports={getList,getDetail,createNewBlog,updataedBlog,deleteBlogData};
